package com.hudson.store.util;

import com.hudson.store.commitlog.CommitLogManger;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MappedFile {
    private File file;
    private RandomAccessFile randomAccessFile;
    private FileChannel fileChannel;
    private MappedByteBuffer mappedByteBuffer;
    private long currentOffset = 0; // 当前写入位置

    public MappedFile(String fileName,long fileSize) {
        this.file = new File(fileName);

        try {
            // 检查并创建父目录
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                parentDir.mkdirs();
            }

            boolean isNewFile = !file.exists();
            if (!file.exists()) {
                file.createNewFile();
            }

            randomAccessFile = new RandomAccessFile(file, "rw");
            fileChannel = randomAccessFile.getChannel();

            // 映射整个文件到内存
            mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize);

//            if (isNewFile) {
//                currentOffset = CommitLogManger.FILE_SIZE * Integer.parseInt(file.getName().substring(0, file.getName().lastIndexOf("."))) + 8;
//
//                mappedByteBuffer.position(0);
//                mappedByteBuffer.putLong(currentOffset);
//                System.out.println(currentOffset);
//            } else {
//                // 从文件头读取保存的 offset
//                mappedByteBuffer.position(0);
//                currentOffset = CommitLogManger.FILE_SIZE * Integer.parseInt(file.getName().substring(0, file.getName().lastIndexOf("."))) + mappedByteBuffer.getLong();
//                System.out.println(currentOffset);
//            }

        } catch (IOException e) {
            throw new RuntimeException("Failed to map file: " + fileName, e);
        }
    }

    // 获取实际数据大小
    public int getActualSize() {
        return mappedByteBuffer.position();
    }

    /**
     * 强制刷盘
     */
    public void flush() {
        mappedByteBuffer.force(); // 或使用 force()
    }

    /**
     * 关闭资源
     */
    public void close() throws IOException {
        flush(); // 确保 offset 写入磁盘
        fileChannel.close();
        randomAccessFile.close();
    }

    public boolean isFull(int size) {
        return currentOffset + size >
                CommitLogManger.FILE_SIZE * (Integer.parseInt(file.getName().substring(0, file.getName().lastIndexOf("."))) + 1);
    }

    public String getFileName() {
        return file.getName();
    }

    public long getCurrentOffset() {
        return currentOffset;
    }

    public MappedByteBuffer getMappedByteBuffer() {
        return mappedByteBuffer;
    }
}
